package cn.semes.org.controller;


import cn.semes.basic.util.AjaxResult;
import cn.semes.basic.util.FastdfsUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * fastdfs 接口
 */
@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {


    /**
     * 上传
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file) throws IOException {
        /// 真实路径
        String originalFilename = file.getOriginalFilename();
        // 获取扩展名
        String extension = FilenameUtils.getExtension(originalFilename);
        // 执行上传
        String path = FastdfsUtil.upload(file.getBytes(), extension);
        return AjaxResult.me().success(path);
    }

    /**
     * 删除
     */

    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path) throws IOException {
        // /group1/M00/02/ED/CgAIC2N526-AffczAAIbh_fh03I613.jpg
        // group1/M00/02/ED/CgAIC2N526-AffczAAIbh_fh03I613.jpg
        String allPath = path.substring(1);
        // group1
        String groupName = allPath.substring(0, allPath.indexOf("/"));
        // M00/02/ED/CgAIC2N526-AffczAAIbh_fh03I613.jpg
        String pathName = allPath.substring(allPath.indexOf("/") + 1);
        FastdfsUtil.delete(groupName, pathName);
        return AjaxResult.me().success(path);
    }
}